package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.BangDingFamilyDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyMemberVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author Tomorrow
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInMapper checkInMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    /**
     * 小程序登录验证
     *
     * @param userLoginRequestDto
     * @return 返回token和nickName
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //调用微信官方接口获取openId
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());

        //根据openId查询数据库获取用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getOpenId, openid));


        //如果用户信息不存在，就创建一个用户，并绑定openId
        if (ObjectUtil.isEmpty(familyMember)) {

            //用户不存在,创建一个新用户
            familyMember = new FamilyMember();
            familyMember.setOpenId(openid);

        }

        //调用微信接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        familyMember.setPhone(phoneNumber);

        //保存或更新用户
        saveOrUpdateFamilyMember(familyMember);


        LoginVo loginVo = new LoginVo();
        Map<String, Object> claims = new HashMap<>();

        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        //封装用户信息到token中，返回给小程序
        String token = tokenService.createToken(claims);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());


        return loginVo;
    }

    /**
     * 根据主键Id判断该用户是新增还是修改
     *
     * @param familyMember 老人家属
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {

        //判断老人家属主键Id是否存在
        if (ObjectUtil.isEmpty(familyMember.getId())) {

            //新增
            //在数组中随机选择一个名字，拼接上手机号后四位
            String prefix = DEFAULT_NICKNAME_PREFIX.get((int) Math.random() * DEFAULT_NICKNAME_PREFIX.size());
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {

            //修改
            familyMemberMapper.updateById(familyMember);

        }
    }


    /**
     * 小程序绑定家人（新增老人家属）
     *
     * @param bangDingFamilyDto
     * @return 结果
     */
    @Override
    public void add(BangDingFamilyDto bangDingFamilyDto) {

        //先根据老人IdCardNo查询入住表中的老人是否存在，不存在直接结束
        CheckIn checkIn = checkInMapper.selectOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getIdCardNo, bangDingFamilyDto.getIdCard())
                .eq(CheckIn::getElderName, bangDingFamilyDto.getName()));
        if (ObjectUtil.isEmpty(checkIn)) {
            throw new BaseException("绑定的老人尚未入住，请入住后再绑定");
        }

        //判断该用户是否与该老人绑定过，如过绑定过，直接返回
        int count = checkInMapper.selectBinding(bangDingFamilyDto);
        if (count > 0) {
            throw new BaseException("与该老人已绑定，请勿重复绑定");
        }

        //相同保存到家属表
        Long userId = UserThreadLocal.getUserId();

        FamilyMemberElder familyMemberElder = BeanUtil.toBean(bangDingFamilyDto, FamilyMemberElder.class);
        familyMemberElder.setElderId(checkIn.getElderId());
        familyMemberElder.setFamilyMemberId(userId);

        try {

            familyMemberMapper.insertElderFamily(familyMemberElder);
        } catch (Exception e) {
            throw new BaseException("保存失败");
        }

    }

    /**
     * 小程序查询家人列表
     *
     * @return
     */
    @Override
    public List<FamilyMemberVo> selectFamilyMember() {

        ////查询到当前登录用户的ID
        Long userId = UserThreadLocal.getUserId();

        //查询到当前登录用户在客户老人关联表中的信息
        List<FamilyMemberVo> familyMemberVos = familyMemberMapper.selectFamilyMemberElder(userId);

        //遍历集合，查询老人姓名，并添加到familyMemberVo中
        familyMemberVos.forEach(familyMemberVo -> {
            String elderName = elderMapper.selectElderById(familyMemberVo.getElderId()).getName();
            familyMemberVo.setElderName(elderName);
        });


        return familyMemberVos;
    }



}



/*   *//**
 * 查询老人家属
 *
 * @param id 老人家属主键
 * @return 老人家属
 * <p>
 * 查询老人家属列表
 * @param familyMember 老人家属
 * @return 老人家属
 * <p>
 * 修改老人家属
 * @param familyMember 老人家属
 * @return 结果
 * <p>
 * 批量删除老人家属
 * @param ids 需要删除的老人家属主键
 * @return 结果
 * <p>
 * 删除老人家属信息
 * @param id 老人家属主键
 * @return 结果
 * <p>
 * 查询老人家属列表
 * @param familyMember 老人家属
 * @return 老人家属
 * <p>
 * 修改老人家属
 * @param familyMember 老人家属
 * @return 结果
 * <p>
 * 批量删除老人家属
 * @param ids 需要删除的老人家属主键
 * @return 结果
 * <p>
 * 删除老人家属信息
 * @param id 老人家属主键
 * @return 结果
 * <p>
 * 查询老人家属列表
 * @param familyMember 老人家属
 * @return 老人家属
 * <p>
 * 修改老人家属
 * @param familyMember 老人家属
 * @return 结果
 * <p>
 * 批量删除老人家属
 * @param ids 需要删除的老人家属主键
 * @return 结果
 * <p>
 * 删除老人家属信息
 * @param id 老人家属主键
 * @return 结果
 *//*
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    *//**
 * 查询老人家属列表
 *
 * @param familyMember 老人家属
 * @return 老人家属
 *//*
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    *//**
 * 修改老人家属
 *
 * @param familyMember 老人家属
 * @return 结果
 *//*
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    *//**
 * 批量删除老人家属
 *
 * @param ids 需要删除的老人家属主键
 * @return 结果
 *//*
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    *//**
 * 删除老人家属信息
 *
 * @param id 老人家属主键
 * @return 结果
 *//*
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }*/


